﻿using System.Threading;

namespace HirelSeriesH
{
    class WelcomeHelper
    {
        #region 相关变量定义
        /// <summary>
        /// 定义委托进行窗口关闭
        /// </summary>
        private delegate void CloseDelegate();
        private static WelcomeForm welcomeForm;
        private static readonly object syncLock = new object();  //加锁使用
        //private static IWin32Window owner;
        //public static IWin32Window Owner { get => owner; set => owner = value; }
        #endregion

        /// <summary>
        /// 显示loading框
        /// </summary>
        public static void ShowLoadingScreen()
        {
            // Make sure it is only launched once.
            if (welcomeForm != null)
                return;
            Thread thread = new Thread(new ThreadStart(ShowForm));
            thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
        /// <summary>
        /// 显示窗口
        /// </summary>
        private static void ShowForm()
        {
            if (welcomeForm != null)
            {
                welcomeForm.closeOrder();
                welcomeForm = null;
            }
            welcomeForm = new WelcomeForm();
            welcomeForm.TopMost = true;
            //loadingForm.ShowDialog(Owner);
            welcomeForm.ShowDialog();
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        public static void CloseForm()
        {
            Thread.Sleep(50); //可能到这里线程还未起来，所以进行延时，可以确保线程起来，彻底关闭窗口
            if (welcomeForm != null)
            {
                lock (syncLock)
                {
                    Thread.Sleep(50);
                    if (welcomeForm != null)
                    {
                        Thread.Sleep(50);  //通过三次延时，确保可以彻底关闭窗口
                        welcomeForm.Invoke(new CloseDelegate(CloseFormInternal));
                    }
                }
            }
        }
        /// <summary>
        /// 关闭窗口，委托中使用
        /// </summary>
        private static void CloseFormInternal()
        {
            welcomeForm.closeOrder();
            welcomeForm = null;
        }



    }
}
